import UIKit

public class ImageHandler {
    // MARK: - Properties
    private let containerWidth: CGFloat
    private let placeholderImage: UIImage
    
    // MARK: - Initialization
    public init(containerWidth: CGFloat) {
        self.containerWidth = containerWidth
        
        // 创建默认的占位图
        let config = UIImage.SymbolConfiguration(pointSize: 40, weight: .light)
        self.placeholderImage = UIImage(systemName: "photo", withConfiguration: config)?
            .withTintColor(.systemGray4, renderingMode: .alwaysOriginal) ?? UIImage()
    }
    
    // MARK: - Public Methods
    public func createImageView(url: URL?, title: String? = nil) -> UIImageView {
        let imageView = ResponsiveImageView(maxWidth: containerWidth)
        imageView.contentMode = .scaleAspectFit
        imageView.backgroundColor = .systemGray6
        imageView.layer.cornerRadius = 8
        imageView.clipsToBounds = true
        
        // 设置占位图
        imageView.image = placeholderImage
        
        // 如果有URL，加载图片
        if let url = url {
            loadImage(from: url, into: imageView)
        }
        
        return imageView
    }
    
    private func loadImage(from url: URL, into imageView: ResponsiveImageView) {
        URLSession.shared.dataTask(with: url) { [weak imageView] data, response, error in
            guard let data = data, let image = UIImage(data: data) else {
                return
            }
            
            DispatchQueue.main.async {
                imageView?.setImage(image)
            }
        }.resume()
    }
}

// MARK: - ResponsiveImageView
private class ResponsiveImageView: UIImageView {
    private let maxWidth: CGFloat
    
    init(maxWidth: CGFloat) {
        self.maxWidth = maxWidth
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setImage(_ image: UIImage) {
        self.image = image
        updateImageSize()
    }
    
    private func updateImageSize() {
        guard let image = image else { return }
        
        let aspectRatio = image.size.width / image.size.height
        let targetWidth = min(maxWidth, image.size.width)
        let targetHeight = targetWidth / aspectRatio
        
        // 更新frame
        frame.size = CGSize(width: targetWidth, height: targetHeight)
        
        // 如果使用自动布局��更新约束
        if let constraint = constraints.first(where: { $0.firstAttribute == .width }) {
            constraint.constant = targetWidth
        } else {
            widthAnchor.constraint(equalToConstant: targetWidth).isActive = true
        }
        
        if let constraint = constraints.first(where: { $0.firstAttribute == .height }) {
            constraint.constant = targetHeight
        } else {
            heightAnchor.constraint(equalToConstant: targetHeight).isActive = true
        }
    }
    
    override var intrinsicContentSize: CGSize {
        if let image = image {
            let aspectRatio = image.size.width / image.size.height
            let targetWidth = min(maxWidth, image.size.width)
            let targetHeight = targetWidth / aspectRatio
            return CGSize(width: targetWidth, height: targetHeight)
        }
        return CGSize(width: maxWidth, height: maxWidth * 0.75) // 默认宽高比 4:3
    }
} 